package com.xinkao.example.service.impl;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.xinkao.example.dao.LoginDao;
import com.xinkao.example.service.LoginService;
import com.xinkao.example.util.CommonUtil;
import com.xinkao.example.util.RedisUtils;
import com.xinkao.example.util.constants.Constants;
import com.xinkao.example.util.constants.ErrorEnum;
import com.xinkao.example.util.model.MenuTree;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: LXF
 * @description: 登录service实现类
 * @date: 2017/10/24 11:53
 */
@Service
public class LoginServiceImpl implements LoginService {

	@Resource
	private LoginDao loginDao;

	@Resource
	private RedisUtils redisUtils;

	/**
	 * 登录表单提交
	 */
	@Override
	public JSONObject authLogin(JSONObject jsonObject,String key) {
		String username = jsonObject.getString("username");
		String password = jsonObject.getString("password");
		SimpleHash simpleHashPassword =
				new SimpleHash(Constants.ENCRYPTION, password,null,Constants.TIMES);
		JSONObject info = new JSONObject();
		//每个请求创建一个Subject，并绑定到当前线程。
		Subject currentUser = SecurityUtils.getSubject();
		// 设置凭证永不过期
		currentUser.getSession().setTimeout(-1000L);
		//创建token
		UsernamePasswordToken usernamePasswordToken = new UsernamePasswordToken(username, simpleHashPassword.toString());
		try {
			//通过subject将token传入shiro
			currentUser.login(usernamePasswordToken);
			//登录成功返回token
			info.put("token", currentUser.getPrincipal());
			redisUtils.del(key);
			return CommonUtil.successJson(info);
		} catch (AuthenticationException e) {
			return CommonUtil.errorJson(ErrorEnum.E_503);
		}
	}

	/**
	 * 根据用户名和密码查询对应的用户
	 */
	@Override
	public JSONObject getUser(String username, String password) {
		return loginDao.getUser(username, password);
	}


	/**
	 * 退出登录
	 */
	@Override
	public JSONObject logout() {
		try {
			Subject currentUser = SecurityUtils.getSubject();
			currentUser.logout();
		} catch (Exception e) {
		}
		return CommonUtil.successJson();
	}


	/**
	 * 权限菜单
	 * @param parentId
	 * @return
	 */
	public JSONObject getUserInfo(JSONObject user){
		JSONArray permsList = new JSONArray();
		JSONArray pathList = new JSONArray();
		List<MenuTree> menuList = new ArrayList<>();
		if(user.getString("isSuper").equals("1")){
			menuList = loginDao.getAllMenu4Admin();
		}else {
			menuList = loginDao.getAllMenu4User(user.getString("userId"));
		}
		for(MenuTree menu : menuList){
			String menuType = menu.getMenuType();
			if(StrUtil.isNotEmpty(menuType)){
				if(menuType.indexOf("M") >= 0 || menuType.indexOf("C") >= 0){
					pathList.add(menu.getPath());
				}
				if(menuType.indexOf("F") >= 0 ){
					permsList.add(menu.getPerms());
				}
			}
		}
		user.put("btn", permsList);
		user.put("menu", pathList);
		return user;
	}

	/**
	 * 用户权限
	 * @param userId
	 * @return
	 */
	@Override
	public List<String> getUserPermission(String userId) {
		return loginDao.getUserPermission(userId);
	}
}
